package game.module.sss.procesor;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.sss.bean.SssRound;
import game.module.sss.logic.SssDataManager;
import game.module.sss.logic.SssLogic;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageSss.C2SSssRoundEnd;
import lua.LuaMessageSss.S2CSssRoundEnd;

@MsgCodeAnn(msgcode = C2SSssRoundEnd.id, accessLimit = 500)
public class SssEndRoundProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(SssEndRoundProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		int playerId = playingRole.getId();
		logger.info("sss end round,playerId={}", playerId);
		// 房间是否存在
		final SssRound ddzRound = SssDataManager.getInstance().getNnRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode retMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		// 所有人配牌完成
		boolean isPeiPaiAllFinish = ddzRound.getPeiPaiFinish().size() >= ddzRound.getPlayerIds().size() ? true : false;
		if (!isPeiPaiAllFinish) {
			S2ErrorCode retMsg = new S2ErrorCode(406);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		Set<Integer> nextRoundReadySet = ddzRound.getNextRoundReady();
		if (nextRoundReadySet != null && nextRoundReadySet.contains(playerId)) {
			S2ErrorCode retMsg = new S2ErrorCode(407);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		// do
		if (nextRoundReadySet == null) {
			nextRoundReadySet = new HashSet<>();
			ddzRound.setNextRoundReady(nextRoundReadySet);
		}
		nextRoundReadySet.add(playerId);
		// send
		S2CSssRoundEnd respMsg = new S2CSssRoundEnd();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		// 下回合开始判断
		if (nextRoundReadySet.size() >= ddzRound.getPlayerIds().size()) {
			if (ddzRound.getCurrentRound() >= ddzRound.getRoundCount()) {
				//
				logger.info("sss所有回合结束！");
			} else {
				SssLogic.getInstance().nextRound(ddzRound);
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
